<?php
/**
 * Created by PhpStorm.
 * User: Sergey
 * Date: 14.03.14
 * Time: 17:46
 */

include_once BASE_DQ_PLUGIN_PATH . "classes/Config.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/ConnectionFactory.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/Question.php";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

class QuestionDao extends ConnectionFactory
{
    /**
     * @param $row
     * @return Question
     */
    public function fetch($row)
    {
        try {
            $question = new Question();
            $question->id = $row->id;
            $question->content = $row->content;
            $question->quizId = $row->quiz_id;
            return $question;
        } catch (Exception $ex) {
            return null;
        }
    }

    /**
     * @return array Question
     */
    public function getAll()
    {
        $result = $this->getAllRows(Config::get()->getQuestionsTableName());
        $questions = array();
        foreach ($result as $row) {
            $questions[] = $this->fetch($row);
        }
        return $questions;
    }

    public function getAllByQuizId($quizId)
    {
        $table = Config::get()->getQuestionsTableName();
        $query = "SELECT * FROM $table WHERE quiz_id=$quizId";

        global $wpdb;
        $result = $wpdb->get_results($query);

        $questions = array();
        foreach ($result as $row) {
            $questions[] = $this->fetch($row);
        }
        return $questions;
    }

    /**
     * @param int $id
     * @return null|Question
     */
    public function getById($id)
    {
        $row = $this->getRow(Config::get()->getQuestionsTableName(), $id);
        return $this->fetch($row);
    }

    /**
     * @param Question $question
     */
    public function add(Question $question)
    {
        global $wpdb;
        $wpdb->insert(
            Config::get()->getQuestionsTableName(),
            array(
                "content" => $question->content,
                "quiz_id" => $question->quizId
            ),
            array("%s", "%d")
        );
        return $wpdb->insert_id;
    }

    /**
     * @param Question $question
     */
    public function edit(Question $question)
    {
        global $wpdb;
        $wpdb->update(
            Config::get()->getQuestionsTableName(),
            array(
                "content" => $question->content,
                "quiz_id" => $question->quizId
            ),
            array("id" => $question->id),
            array("%s", "%d"),
            array('%d')
        );
    }

    /**
     * @param int $id
     */
    public function remove($id)
    {
        $this->removeRow(
            Config::get()->getQuestionsTableName(),
            $id
        );
    }
} 